package com.shebei.api.equipment_api_test.service.jacoco;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.shebei.api.equipment_api_test.dao.JacocoReportDAO;
import com.shebei.api.equipment_api_test.dao.SuperJacocoDAO;
import com.shebei.api.equipment_api_test.dao.TestVersionRecordDAO;
import com.shebei.api.equipment_api_test.dao.VersionControlDao;
import com.shebei.api.equipment_api_test.http.HttpClientGet;
import com.shebei.api.equipment_api_test.model.*;
import com.shebei.api.equipment_api_test.model.responseModel.NavigateNameNode;
import com.shebei.api.equipment_api_test.utils.GetLinuxTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class JacocoTestVersionService {

   @Autowired
    private VersionControlDao versionControlDao;
    @Autowired
   private JacocoReportDAO jacocoReportDAO;
    @Autowired
    private TestVersionRecordDAO testVersionRecordDAO;

    @Autowired
    HttpClientGet httpClientGet;

    @Autowired
    SuperJacocoDAO superJacocoDAO;
    @Autowired
    GetLinuxTime getLinuxTime;

    public String versionControlAdd(String moduleName,String testVersion){
        Boolean isExit=isExist(moduleName,testVersion);
        if(isExit){
            return "版本已经存在，请重新命名";
        }
        Date now =new Date();
        long timestamp=now.getTime();
        String uniqueNo=String.valueOf(timestamp);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateNowStr = sdf.format(now );
        VersionControl versionControl=new VersionControl();
        versionControl.setModuleName(moduleName.trim());
        versionControl.setTestVersion(testVersion.trim());
        versionControl.setCreateTime(now);
        versionControl.setIsDelete(0);
       int res= versionControlDao.insert(versionControl);
       if(res==1){
           return "success";
       }
        return "数据插入失败";
    }

    private boolean isExist(String moduleName,String testVersion){
        VersionControl versionControl=new VersionControl();
        versionControl.setModuleName(moduleName);
        versionControl.setTestVersion(testVersion);
        List<VersionControl> res=versionControlDao.selectVersions(versionControl);
        if(res.size()>0){
            return true;
        }
        return false;
    }

    public int versionControlEdit(Integer id,String testVersion,Integer isDelete){
        Date now =new Date();
        long timestamp=now.getTime();
        String uniqueNo=String.valueOf(timestamp);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateNowStr = sdf.format(now );
        VersionControl versionControl=new VersionControl();
        versionControl.setId(id);
        if(testVersion!=null){
            versionControl.setTestVersion(testVersion.trim());
        }

        versionControl.setIsDelete(isDelete);
        int res= versionControlDao.updateByPrimaryKeySelective(versionControl);
        return res;
    }


    public  String versionControlSelect(String moduleName){
        List<NavigateNameNode>  navigateNameNodes=new ArrayList<NavigateNameNode>();
        VersionControl versionControl=new VersionControl();
        versionControl.setModuleName(moduleName);
        List<VersionControl> parents= versionControlDao.selectVersions(versionControl);

        for(VersionControl iter:parents){
            NavigateNameNode tmp= new NavigateNameNode();
            tmp.setId(iter.getId());
            tmp.setLabel(iter.getTestVersion());
            tmp.setModuleName(iter.getModuleName());
            tmp.setIsDelete(iter.getIsDelete());
            navigateNameNodes.add(tmp);

        }
        String res = JSONArray.toJSONString(navigateNameNodes);
        System.out.println(res);
        return res;
    }

   public String getLastUUid(ServerJacocoManager serverJacocoManager,Integer versionId){
          String baseVersion=serverJacocoManager.getBaseVersion();
          String nowVersion=serverJacocoManager.getNowVersion();
          String  moduleName=serverJacocoManager.getModuleName();
          String serverName=serverJacocoManager.getServerName();
          String reportResult="success";
          String jacocoType=serverJacocoManager.getJacocoType();
          TestVersionRecord jacocoReport=new TestVersionRecord();
       jacocoReport.setBaseVersion(baseVersion);
       jacocoReport.setModuleName(moduleName);
       jacocoReport.setServerName(serverName);
       jacocoReport.setNowVersion(nowVersion);
       jacocoReport.setReportResult(reportResult);
       jacocoReport.setvId(versionId);
       if(jacocoType.equals("1")){
           jacocoReport.setJacocoType("全量覆盖率");
       }else {
           jacocoReport.setJacocoType("增量覆盖率");
       }
       List<TestVersionRecord> list= testVersionRecordDAO.selectLastUUid(jacocoReport);
        if(list.size()>0){
            return list.get(0).getUuidRecord();
        }
        return null;
   }


   public void  addReport(ServerJacocoManager serverJacocoManager,long uuid,Integer versionId,String lastUuid){
        String jacocoReport=serverJacocoManager.getJacocoType();
       TestVersionRecord testVersionRecord=new TestVersionRecord();
       testVersionRecord.setUuidRecord(String.valueOf(uuid));
       testVersionRecord.setModuleName(serverJacocoManager.getModuleName());
       testVersionRecord.setServerName(serverJacocoManager.getServerName());
       testVersionRecord.setBaseVersion(serverJacocoManager.getBaseVersion());
       testVersionRecord.setNowVersion(serverJacocoManager.getNowVersion());
       String testVersion=getTestVersion(versionId);
       testVersionRecord.setTestVersion(testVersion);
       testVersionRecord.setvId(versionId);
       testVersionRecord.setLastUuidRecord(lastUuid);
       testVersionRecord.setJacocoServerId(serverJacocoManager.getSuperJacocoId());
       if(jacocoReport.equals("1")){
           testVersionRecord.setJacocoType("全量覆盖率");
       }else {
           testVersionRecord.setJacocoType("增量覆盖率");
       }

       testVersionRecord.setCreateTime(getLinuxTime.getData());
       testVersionRecord.setReportResult("统计中");
       testVersionRecordDAO.insert(testVersionRecord);
   }


    public int updateReport(String uuid){

        // String url=GetConfig.getAddress("jacocoServer").trim()+"/cov/getEnvCoverResult";
        String url=getJacocoSeverUrl(uuid).trim()+"/cov/getEnvCoverResult";
        JSONObject jsonParam= new JSONObject();

        jsonParam.put("uuid",uuid);
        String   res= httpClientGet.sendGetRequset(url,jsonParam.toJSONString(),null);
        // System.out.println("获取报告response："+res);
        Map param = JSONObject.parseObject(res);
        JSONObject data= (JSONObject) ((JSONObject) param).get("data");

        String errMsg=data.getString("errMsg");
        String reportUrl=data.getString("reportUrl");
        System.out.println("报告获取。。。+" +reportUrl +" error:"+errMsg);
        TestVersionRecord testVersionRecord=new TestVersionRecord();
        testVersionRecord.setUuidRecord(uuid);
        testVersionRecord.setLastestReport(reportUrl);
        testVersionRecord.setUpdateTime(getLinuxTime.getData());
        if(reportUrl!=null && reportUrl.contains("index.html")){

            testVersionRecord.setReportResult("success");
            testVersionRecord.setErrMsg(errMsg);

        }else {
            testVersionRecord.setReportResult(errMsg);
            testVersionRecord.setErrMsg(errMsg);
        }
        int res1= testVersionRecordDAO.updateByUuid(testVersionRecord);

        return res1;
    }

    private String getJacocoSeverUrl(String uuid){
        TestVersionRecord report= testVersionRecordDAO.selectByUUid(uuid);
       // Integer jacocoId=report.getvId();
        Integer jacocoSeverId=report.getJacocoServerId();
        SuperJacoco jacoco= superJacocoDAO.selectByPrimaryKey(jacocoSeverId);
        String url=jacoco.getJacocoServer();
        return url;

    }

    private String getTestVersion(Integer versionId){
       VersionControl versionControl= versionControlDao.selectByPrimaryKey(versionId);
       return versionControl.getTestVersion();
    }
}
